package net.uhuijia.filter;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;
import net.uhuijia.appbase.redis.IRedisDao;
import net.uhuijia.enums.ErrorCodeEnum;
import net.uhuijia.enums.RedisKey;
import net.uhuijia.enums.UserAuth;
import net.uhuijia.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import net.uhuijia.config.ProjectConfigYmlHelper;
import net.uhuijia.config.ZuulIgnoredUrlsHelper;
import net.uhuijia.user.usermall.clientservice.UserMallClientService;
import net.uhuijia.user.usermall.persistence.model.UserMall;

@Configuration
public class AccessGatewayFilter extends ZuulFilter {
    //private static final String ignoredUrls []= {"http://192.168.1.110:9527/test/testdemo/get"};
    @Autowired
    private UserMallClientService userMallClientService;
    @Autowired
    private IRedisDao<String,Object> redisDao;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext() ;
        HttpServletRequest request = ctx.getRequest() ;
        //System.out.println(request.getMethod()+request.getRequestURL().toString());
       // _logger.info("send {} to {}",request.getMethod(),request.getRequestURL().toString());
        String url = request.getRequestURL().toString();
        boolean isIgnoredUrl = isIgnoredUrls(url);
        String token = (String)request.getParameter("token") ;
        String device = (String)request.getParameter("device") ;
        boolean isAuthPass = isAuthPass(token,device);
        /** 效验是或否是忽略路径 是否授权通过*/
        if(isIgnoredUrl || isAuthPass){
            ctx.setSendZuulResponse(true);// 对该请求进行路由
            ctx.setResponseStatusCode(200);
            ctx.set("isSuccess", true);//
            addZuulRequestHeader(token,device);
        }else{
            JSONObject r = new JSONObject();
            r.put("code", "9999");
            r.put("msg", "zuul filter fail!");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody(r.toString());// 返回错误内容
            ctx.set("isSuccess", false);//
        }
        return null;
    }

    /**
     * 效验是否是忽略路径
     * @param url 路径
     * @return
     */
    public boolean isIgnoredUrls(String url){
        if(StringUtils.isEmpty(url))
            return false;
        String[] ignoredurls = ZuulIgnoredUrlsHelper.getIgnoredurls();
        String valueByName = ProjectConfigYmlHelper.getValueByName("zuul.domain");
        for(String ignoredUrl : ignoredurls){
            if( url.contains(valueByName+ignoredUrl) ){
            	return true;
            }
        }
        return false;
    }

    /**
     * 验证token的有效性
     * @param token
     * @param device
     * @return
     */
    public boolean isAuthPass(String token,String device){
        boolean isAuthPass = true;
        if(!StringUtils.isNoneBlank(token,device)){
            isAuthPass = false;
        }else{
            StringBuffer authKey = new StringBuffer(RedisKey.USER_TOKEN_DEVICE_AUTH.getKey());
            authKey.append(token).append(device);
            UserMall user = (UserMall) this.redisDao.get(authKey.toString());
            if( null == user ){
                user = userMallClientService.auth(device, token);
                if(user==null){
                    isAuthPass = false;
                }else{
                    this.redisDao.set(authKey.toString(),user,1*24*60*60L);
                }
            }
        }
        return isAuthPass;
    }

    /**
     * 将token 和devicen添加进zuulHeader
     * 方便接口获取
     * @param token
     * @param device
     */
    public void addZuulRequestHeader(String token,String device){
        RequestContext requestContext = RequestContext.getCurrentContext();
        requestContext.addZuulRequestHeader(UserAuth.token.toString(),token);
        requestContext.addZuulRequestHeader(UserAuth.device.toString(),device);
    }


}
